<!--
  * 供应商信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-24 18:44:02
  * @Copyright  lmabbe
-->
<template>
  <a-modal
    :destroyOnClose="true"
    :maskClosable="false"
    :open="visibleFlag"
    :title="form.supplierCode ? '编辑' : '添加'"
    :width="550"
    @cancel="onClose"
  >
    <a-form ref="formRef" :label-col="{ span: 5 }" :model="form" :rules="rules">
      <a-form-item label="供应商编码" name="supplierCode">
        <a-input v-model:value="form.supplierCode" placeholder="供应商编码" style="width: 100%" />
      </a-form-item>
      <a-form-item label="供应商名称" name="supplierName">
        <a-input v-model:value="form.supplierName" placeholder="供应商名称" style="width: 100%" />
      </a-form-item>
      <a-form-item label="供应商简称" name="supplierAbbreviation">
        <a-input v-model:value="form.supplierAbbreviation" placeholder="供应商简称" style="width: 100%" />
      </a-form-item>
      <a-form-item label="归属客户" name="belongCustomer">
        <a-select
          v-model:value="form.belongCustomer"
          :allowClear="true"
          :style="`width: 100%`"
          placeholder="请选择归属客户"
          @change="
            (value) => {
              form.belongCustomerAbbreviation = customerData.find((item) => item.customerCode === value).customerAbbreviation;
            }
          "
        >
          <a-select-option v-for="item in customerData" :key="item.customerCode" :value="item.customerCode">
            {{ item.customerAbbreviation }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="供应商地址" name="supplierAddress">
        <a-input v-model:value="form.supplierAddress" placeholder="供应商地址" style="width: 100%" />
      </a-form-item>
      <a-form-item label="联系方式" name="contactInformationJson">
        <a-space v-for="(user, index) in form.contactInformationJson" :key="index" align="baseline">
          <a-form-item :name="['contactInformationJson', index, 'contactName']" :rules="{ required: true, message: '联系人必填' }">
            <a-input v-model:value="user.contactName" placeholder="联系人" />
          </a-form-item>
          <a-form-item :name="['contactInformationJson', index, 'contactPhone']" :rules="{ required: true, message: '联系人电话必填' }">
            <a-input v-model:value="user.contactPhone" placeholder="联系电话" />
          </a-form-item>
          <a-form-item :name="['contactInformationJson', index, 'contactPosition']">
            <a-input v-model:value="user.contactPosition" placeholder="联系人职位" />
          </a-form-item>
          <MinusCircleOutlined @click="removeUser(user)" />
        </a-space>
        <a-form-item>
          <a-button block type="dashed" @click="addUser">
            <PlusOutlined />
            添加联系人
          </a-button>
        </a-form-item>
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { supplierInfoApi } from '/@/api/business/basic/supplier/supplier-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js'; // ------------------------ 事件 ------------------------

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  const addFlag = ref(false);

  function show(rowData) {
    addFlag.value = !Object.prototype.hasOwnProperty.call(rowData, 'supplierCode');
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    if (!addFlag.value) {
      form.contactInformationJson = JSON.parse(form.contactInformation);
    }
    customerAll();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    supplierCode: undefined, //供应商编码
    supplierName: undefined, //供应商名称
    supplierAbbreviation: undefined, //供应商简称
    belongCustomer: undefined, //归属客户
    belongCustomerAbbreviation: undefined,
    supplierAddress: undefined, //供应商地址
    contactInformation: undefined, //联系方式
    contactInformationJson: [],
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    supplierCode: [{ required: true, message: '供应商编码 必填' }],
    supplierName: [{ required: true, message: '供应商名称 必填' }],
    supplierAbbreviation: [{ required: true, message: '供应商简称 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      form.contactInformation = JSON.stringify(form.contactInformationJson);
      if (!addFlag.value) {
        await supplierInfoApi.update(form);
      } else {
        await supplierInfoApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  function addUser() {
    form.contactInformationJson.push({
      contactName: '',
      contactPhone: '',
      contactPosition: '',
    });
  }

  function removeUser(data) {
    form.contactInformationJson.splice(form.contactInformationJson.indexOf(data), 1);
  }

  const customerData = ref();

  function customerAll() {
    customerInfoApi.customerAll().then((res) => {
      customerData.value = res.data;
    });
  }

  defineExpose({
    show,
  });
</script>